package com.dts.yjnb.service.service.impl;

import com.dts.common.core.page.TableDataInfo;
import com.dts.yjnb.service.domain.Market;
import com.dts.yjnb.service.domain.NbAllowancePolicy;
import com.dts.yjnb.service.domainDto.AllowancePolicyDTO;
import com.dts.yjnb.service.domainVo.AllowancePolicyVo;
import com.dts.yjnb.service.mapper.NbAllowancePolicyMapper;
import com.dts.yjnb.service.domainVo.AppAllowancePolicyVo;


import com.dts.common.core.page.TableDataInfo;
import com.github.pagehelper.Page;
import com.dts.common.utils.PageRequest;
import com.dts.common.utils.PageResponse;
import com.dts.common.utils.PageUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dts.yjnb.service.service.INbAllowancePolicyService;

import java.util.List;

import static com.dts.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 补贴政策Service业务层处理
 *
 * @author jyn
 * @date 2024-09-29
 */
@Service
public class NbAllowancePolicyServiceImpl implements INbAllowancePolicyService
{
    @Autowired
    private NbAllowancePolicyMapper nbAllowancePolicyMapper;

    /**
     * 查询补贴政策列表（管理端）
     *
     * @param allowancePolicyDTO 查询条件
     * @return 补贴政策列表
     */
    @Override
    public List<AllowancePolicyVo> selectAllowancePolicyList(AllowancePolicyDTO allowancePolicyDTO) {
        return nbAllowancePolicyMapper.selectAllowancePolicyList(allowancePolicyDTO);
    }

    /**
     * 查询补贴政策列表（APP端）
     *
     * @param appAllowancePolicyVo 查询条件
     * @param pageRequest 分页请求
     * @return 分页结果
     */
    @Override
    public PageResponse<AppAllowancePolicyVo> appQueryAllowancePolicy(AppAllowancePolicyVo appAllowancePolicyVo, PageRequest pageRequest) {
        return PageUtil.toPage(nbAllowancePolicyMapper.appQueryAllowancePolicy(appAllowancePolicyVo), pageRequest);
    }

    /**
     * 搜索补贴政策信息
     *
     * @param searchDTO 搜索条件（包含标题、作者/来源等搜索参数）
     * @return 分页结果
     */
    @Override
    public TableDataInfo searchAllowancePolicy(AllowancePolicyDTO searchDTO) {
        // 设置默认分页参数
        Integer page = searchDTO.getPage() != null ? searchDTO.getPage() : 1;
        Integer pageSize = searchDTO.getPageSize() != null ? searchDTO.getPageSize() : 10;

        // 打印搜索条件日志
        log.info("执行补贴政策搜索，关键词: {}, 标题: {}, 作者/来源: {}, 页码: {}, 每页条数: {}",
                searchDTO.getKeyword(), searchDTO.getTitle(), searchDTO.getAuthorSource(), page, pageSize);

        // 执行分页查询
        com.github.pagehelper.PageHelper.startPage(page, pageSize);
        List<AllowancePolicyVo> list = nbAllowancePolicyMapper.searchAllowancePolicy(searchDTO);

        // 将List转换为Page对象以获取分页信息
        com.github.pagehelper.Page<AllowancePolicyVo> pageInfo = (com.github.pagehelper.Page<AllowancePolicyVo>) list;

        // 封装返回结果
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setTotal(pageInfo.getTotal());
        tableDataInfo.setRows(pageInfo.getResult());

        log.info("搜索完成，返回结果数量: {}", pageInfo.getTotal());
        return tableDataInfo;
    }

    @Override
    public TableDataInfo pageQuery(AllowancePolicyDTO allowancePolicyDTO) {
        //属性拷贝
        NbAllowancePolicy allowancePolicy = new NbAllowancePolicy();
        BeanUtils.copyProperties(allowancePolicyDTO, allowancePolicy);

        //开始分页
        PageHelper.startPage(allowancePolicyDTO.getPage(), allowancePolicyDTO.getPageSize());
        Page<NbAllowancePolicy> page = nbAllowancePolicyMapper.page(allowancePolicy);

        long total = page.getTotal();
        List<NbAllowancePolicy> records = page.getResult();

        // 创建TableDataInfo对象并设置数据列表
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(records);
        tableDataInfo.setTotal(total);
        return tableDataInfo;
    }

    /**
     * 删除补贴政策（单个或批量）
     *
     * @param ids 补贴政策ID，单个ID或逗号分隔的多个ID（例如："1" 或 "1,2,3"）
     * @return 结果
     */
    @Override
    public int deleteNbAllowancePolicyByIds(String ids) {
        log.info("删除补贴政策，IDs：{}", ids);
        
        if (ids == null || ids.trim().isEmpty()) {
            log.warn("删除失败，ID不能为空");
            return 0;
        }
        
        // 将逗号分隔的字符串转换为数组
        String[] idArray = ids.split(",");
        // 去除每个ID的前后空格
        for (int i = 0; i < idArray.length; i++) {
            idArray[i] = idArray[i].trim();
        }
        
        int result = nbAllowancePolicyMapper.deleteNbAllowancePolicyByIds(idArray);
        log.info("删除补贴政策完成，删除数量: {}", result);
        
        return result;
    }

    /**
     * 新增补贴政策
     *
     * @param allowancePolicyDTO 补贴政策信息
     * @return 结果
     * @throws IllegalArgumentException 当参数验证失败时抛出
     */
    @Override
    public int insertAllowancePolicy(AllowancePolicyDTO allowancePolicyDTO) {
        log.info("新增补贴政策信息: {}", allowancePolicyDTO);

        // 参数验证
        validateAllowancePolicyDTO(allowancePolicyDTO);

        // 设置默认值
        if (allowancePolicyDTO.getViewCount() == null) {
            allowancePolicyDTO.setViewCount(0);
        }

        // 执行插入操作
        int result = nbAllowancePolicyMapper.insertAllowancePolicy(allowancePolicyDTO);
        log.info("新增补贴政策完成，结果: {}", result);

        return result;
    }

    /**
     * 根据ID查询补贴政策详情
     *
     * @param id 补贴政策ID
     * @return 补贴政策DTO
     */
    @Override
    public AllowancePolicyDTO getAllowancePolicyById(String id) {
        log.info("根据ID查询补贴政策详情，ID：{}", id);
        AllowancePolicyDTO allowancePolicyDTO = nbAllowancePolicyMapper.getAllowancePolicyById(id);
        if (allowancePolicyDTO == null) {
            log.warn("未找到ID为{}的补贴政策", id);
        }
        return allowancePolicyDTO;
    }
    
    /**
     * 修改补贴政策
     *
     * @param allowancePolicyDTO 补贴政策信息
     * @return 结果
     * @throws IllegalArgumentException 当参数验证失败时抛出
     */
    @Override
    public int updateAllowancePolicy(AllowancePolicyDTO allowancePolicyDTO) {
        log.info("修改补贴政策信息: {}", allowancePolicyDTO);
        
        // 参数验证
        if (allowancePolicyDTO == null || allowancePolicyDTO.getId() == null) {
            throw new IllegalArgumentException("补贴政策ID不能为空");
        }
        validateAllowancePolicyDTO(allowancePolicyDTO);
        
        // 执行更新操作
        int result = nbAllowancePolicyMapper.updateAllowancePolicy(allowancePolicyDTO);
        log.info("修改补贴政策完成，结果: {}", result);
        
        if (result == 0) {
            log.warn("修改失败，补贴政策ID {} 不存在或已被删除", allowancePolicyDTO.getId());
        }
        
        return result;
    }
    
    /**
     * 单个修改发布状态
     *
     * @param id 补贴政策ID
     * @param status 发布状态：1已发布 0未发布
     */
    @Override
    public void updateStatusById(String id, Integer status) {
        log.info("修改补贴政策发布状态，ID：{}，状态：{}", id, status);
        
        if (id == null || id.trim().isEmpty()) {
            throw new IllegalArgumentException("补贴政策ID不能为空");
        }
        if (status == null || (status != 0 && status != 1)) {
            throw new IllegalArgumentException("发布状态参数错误");
        }
        
        int result = nbAllowancePolicyMapper.updateStatusById(id, status);
        if (result == 0) {
            throw new IllegalArgumentException("修改失败，补贴政策不存在");
        }
        
        log.info("修改补贴政策发布状态成功");
    }
    
    /**
     * 单个修改推荐状态
     *
     * @param id 补贴政策ID
     * @param isRecommend 推荐状态：1推荐 0不推荐
     */
    @Override
    public void updateRecommendById(String id, Integer isRecommend) {
        log.info("修改补贴政策推荐状态，ID：{}，推荐状态：{}", id, isRecommend);
        
        if (id == null || id.trim().isEmpty()) {
            throw new IllegalArgumentException("补贴政策ID不能为空");
        }
        if (isRecommend == null || (isRecommend != 0 && isRecommend != 1)) {
            throw new IllegalArgumentException("推荐状态参数错误");
        }
        
        int result = nbAllowancePolicyMapper.updateRecommendById(id, isRecommend);
        if (result == 0) {
            throw new IllegalArgumentException("修改失败，补贴政策不存在");
        }
        
        log.info("修改补贴政策推荐状态成功");
    }
    
    /**
     * 验证补贴政策DTO
     *
     * @param allowancePolicyDTO 补贴政策信息
     * @throws IllegalArgumentException 当验证失败时抛出
     */
    private void validateAllowancePolicyDTO(AllowancePolicyDTO allowancePolicyDTO) {
        if (allowancePolicyDTO == null) {
            throw new IllegalArgumentException("补贴政策信息不能为空");
        }
        if (allowancePolicyDTO.getTitle() == null || allowancePolicyDTO.getTitle().trim().isEmpty()) {
            throw new IllegalArgumentException("文章标题不能为空");
        }
        if (allowancePolicyDTO.getAuthorSource() == null || allowancePolicyDTO.getAuthorSource().trim().isEmpty()) {
            throw new IllegalArgumentException("作者/来源不能为空");
        }
        if (allowancePolicyDTO.getStatus() == null) {
            throw new IllegalArgumentException("发布状态不能为空");
        }
        if (allowancePolicyDTO.getIsRecommend() == null) {
            throw new IllegalArgumentException("是否推荐不能为空");
        }
    }

}
